#include "../../include/offlinedict/Configuration.h"
#include "../../include/offlinedict/MyLogger.h"

#include <fstream>
#include <iostream>
#include <string.h>
#include <errno.h>

Configuration* Configuration::_pInstance = nullptr;
pthread_once_t Configuration::_once = PTHREAD_ONCE_INIT;

Configuration* Configuration::getInstance()
{
    pthread_once(&_once,init_r);
    return _pInstance;
}

void Configuration::init_r()
{
    if(_pInstance == nullptr)
    {
        _pInstance = new Configuration();
        atexit(destroy);
    }
}

// 配置文件读取
void Configuration::readConfigFile(const string &configFilePath)
{
    ifstream ifs(configFilePath);
    if(!ifs)
    {
        LogError("Error: Unable to open file " + configFilePath);
        LogError("Reason: "+ strerror(errno));
        return;
    }

    // 打开文件成功
    string key;
    string value;
    while(ifs>>key && getline(ifs,value))
    {
        // 去重value前面的一个空格
        if(!value.empty()&&value[0]==' ')
        {
            value = value.substr(1);
        }
        
        _configMap[key] = value;
    }
    
    // 生成停用词表
    createStopWordList();

    ifs.close();
    return ;
}


// 获取配置文件内容
unordered_map<string, string>& Configuration::getConfigMap()
{
    return _configMap;
}  

// 获取key对应的value
string Configuration::getMapValue(const string &key)
{
    auto it = _configMap.find(key);
    if(it == _configMap.end())  // 没查找到
    {
        LogError("Error: 无法找到key对应的value! ");
        return "";
    }
    return it->second;
}


// 生成停用词集合
void Configuration::createStopWordList()
{
    // 获取英文停用词库,放到_stopWordList中
    auto it = _configMap.find("stop_words_eng.txt");
    if(it != _configMap.end())
    {
        ifstream ifs(it->second);
        if(!ifs)
        {
            LogError("Error: Unable to open file "+ it->second);
            LogError("Reason: " + strerror(errno));
            return;
        }

        string line;
        while(getline(ifs,line))
        {
            _stopWordList.insert(line);
        }
        ifs.close();
    }

    // 获取中文停用词库
    it = _configMap.find("stop_words_zh.txt");
    if(it != _configMap.end())
    {
        ifstream ifs(it->second);
        if(!ifs)
        {
            LogError("Error: Unable to open file "+ it->second);
            LogError("Reason: " + strerror(errno));
            return;
        }

        string line;
        while(getline(ifs,line))
        {
            _stopWordList.insert(line);
        }
        ifs.close();
    }

}

// 判断是否是停用词
bool Configuration::isStopWord(const string &word)
{
    auto it = _stopWordList.find(word);
    if(it == _stopWordList.end())  // 没查找到
    {
        return false;
    }
    return true;
}

Configuration::Configuration()
{
    _configMap.clear();
    _stopWordList.clear();
}

Configuration::~Configuration()
{

}

// 释放内存资源
void Configuration::destroy()
{
    if(_pInstance)
    {
        delete _pInstance;
        _pInstance = nullptr;
    }
}
